import React, { useEffect, useState } from "react";
import Hls from "hls.js";
import DPlayer from "dplayer";
// import  abc from "../assets/abc.mp4"

export default function Live() {
  let [msg, setMsg] = useState("消息");
  let [title,setTitle] = useState("标题")
  let [ws, setWS] = useState(new WebSocket("ws://192.168.51.92:8080"));

  let send = () => {
    let info  = {type:1,msg}; 
    ws.send(JSON.stringify(info));
  };

  useEffect(() => {
    //vue中写在mounted
    ws.onmessage = (evt)=>{
      //console.log(evt.data);
      let  data   = evt.data;
      data = JSON.parse(data);
      if(data.type==1){
      let  dplayerDiv = document.getElementById("dplayer");
      dplayerDiv.style.position  ="relative";
      let  div = document.createElement("div");
      div.innerHTML = data.msg;
      let left  = dplayerDiv.offsetWidth+"px";
      let  height = 50+Math.round(Math.random()*200)+"px";
      Object.assign(div.style,{color:"red",position:"absolute",left,top:height});
      dplayerDiv.appendChild(div);

      div.timer  = setInterval(()=>{

       div.style.left = div.offsetLeft -10+"px";
       if(div.offsetLeft<=0){
          clearInterval(div);
          div.remove();
       }
      },300);
    }else if(data.type ==2){
        setTitle(data.msg);
    }else if(data.type ==3){
        window.close();
    }
    }
    const dp = new DPlayer({
      container: document.getElementById("dplayer"),
      live: true,
      video: {
        url: "https://openhls-tct.douyucdn2.cn/dyliveflv1a/288016rlols5_900.m3u8?txSecret=3a9b9a16b776c858b63cf37b10f363d1&txTime=653113ef&token=h5-douyu-0-288016-783614aa53339d06b5505b7e5701b23a&did=4cc1e47428e518017a84418b000416p1&origin=tct&vhost=play2&sid=366965684",
        type: "customHls",
        customType: {
          customHls: function (video, player) {
            const hls = new Hls();
            hls.loadSource(video.src);
            hls.attachMedia(video);
          },
        },
      },
    });
  }, []);

  useEffect(() => {
    return () => {
      console.log("页面离开");
    };
  }, []);

  return (
    <div>
      {title}
      <div id="dplayer" style={{ height: "400px",position:"relative" }}>
      </div>
      <input
        value={msg}
        onChange={(e) => {
          setMsg(e.target.value);
        }}
      />{" "}
      <button
        onClick={() => {
          send();
        }}
      >
        发个消息
      </button>
    </div>
  );
}
